package com.fpx.open.platform.web.manager.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fpx.open.platform.web.manager.FrequencyManager;

/**
 * 频率检查实现类
 * 
 * @author sunkey
 * @date Mar 22, 2013 5:22:04 PM
 * @version 1.0.0
 */
@Component(value = "frequencyManager")
public class FrequencyManagerImpl implements FrequencyManager {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private final static ConcurrentMap<String, int[]> cacheMap = new ConcurrentHashMap<String, int[]>();

	private final ReentrantLock lock = new ReentrantLock();

	/**
	 * @see com.fpx.open.platform.web.manager.FrequencyManager.check
	 */
	public boolean check(String userId, int upperLimit) {
		lock.lock();
		try {
			Long time = System.currentTimeMillis();
			time = time / 60000;
			int currentMinute = time.intValue();
			if (logger.isDebugEnabled()) {
				logger.debug("userId:{}, currentMinute:{}", userId,
						currentMinute);
			}
			if (cacheMap.containsKey(userId)) {
				int[] arr = cacheMap.get(userId);
				int minute = arr[0];
				int amount = arr[1];
				if (minute == currentMinute) {
					amount++;
					arr[1] = amount;
					
					// 大于上限,
					if (amount > upperLimit) {
						if (logger.isInfoEnabled()) {
							logger.info("frequency is more than " + upperLimit
									+ " userId:" + userId + ",amount:" + amount);
						}
						return false;
					}else{
						if (logger.isDebugEnabled()) {
							logger.debug("userId:{},amount:{}", userId, amount);
						}
					}

				} else {
					// 保存的不是当前分钟，设置为当前分钟
					arr[0] = currentMinute;
					arr[1] = 1;
				}
				cacheMap.put(userId, arr);

			} else {
				// 第一次初始化
				int[] arr = new int[2];
				arr[0] = currentMinute;
				arr[1] = 1;
				cacheMap.put(userId, arr);
			}
		} finally {
			lock.unlock();
		}
		return true;
	}

}
